package com.koo.modules.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koo.common.utils.MyStrUtil;
import com.koo.common.utils.PageUtils;
import com.koo.common.utils.Query;
import com.koo.common.utils.UserUtils;
import com.koo.modules.product.dao.ProductInfoDao;
import com.koo.modules.product.entity.ProductAttrEntity;
import com.koo.modules.product.entity.ProductCategoryEntity;
import com.koo.modules.product.entity.ProductInfoEntity;
import com.koo.modules.product.entity.ProductImageEntity;
import com.koo.modules.product.entity.vo.ProductVo;
import com.koo.modules.product.service.ProductAttrService;
import com.koo.modules.product.service.ProductCategoryService;
import com.koo.modules.product.service.ProductImageService;
import com.koo.modules.product.service.ProductInfoService;
import com.koo.modules.base.util.WrapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoDao, ProductInfoEntity> implements ProductInfoService {

    @Autowired
    private ProductAttrService productAttrService;
    @Autowired
    private ProductImageService productImageService;
    @Autowired
    private ProductCategoryService productCategoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        int queryType = Integer.parseInt(params.get("queryType") + "");
        //1、带有查询条件
        if(queryType == 1){
            QueryWrapper<ProductVo> wrapper = new QueryWrapper<>();
            WrapperUtil.initQueryWrapper(params, wrapper);
            IPage<ProductVo> page = new Query<ProductVo>().getPage(params);
            page = baseMapper.listByPageWithParams(page, wrapper);
            return new PageUtils(page);
        }else{
            //2、没有查询条件
            QueryWrapper<ProductInfoEntity> wrapper = new QueryWrapper<>();
            WrapperUtil.initQueryWrapper(params, wrapper);
            IPage<ProductInfoEntity> page = new Query<ProductInfoEntity>().getPage(params);
            page = baseMapper.listByPage(page, wrapper);
            return new PageUtils(page);
        }
    }

    @Override
    public String getMaxCode() {
        String maxCode = baseMapper.selectMaxCode(UserUtils.getStoreId());
        if (MyStrUtil.isEmpty(maxCode)) {
            maxCode = "10000";
        } else {
            maxCode = (Integer.parseInt(maxCode) + 1) + "";
        }
        return maxCode;
    }

    @Override
    public ProductVo findById(Long productId) {
        ProductInfoEntity productEntity = this.getById(productId);
        ProductVo vo = new ProductVo();
        if(productEntity != null){
            BeanUtils.copyProperties(productEntity, vo);
        }

        //1、查询其它属性信息
        ProductAttrEntity attrEntity = productAttrService.getById(productId);

        //2、拷贝其它属性信息
        if(attrEntity != null){
            BeanUtils.copyProperties(attrEntity, vo);
        }

        //3、查询图片
        LambdaQueryWrapper<ProductImageEntity> imgWrapper = new LambdaQueryWrapper<>();
        imgWrapper.eq(ProductImageEntity::getProductId, productEntity.getProductId());
        List<ProductImageEntity> pics = productImageService.list(imgWrapper);
        vo.setPics(pics);

        //4、查询分类信息回显
        Set<Long> cateList = new HashSet<>();
        getAllCateIds(cateList, productEntity.getCategoryId());
        //5、倒循序
        cateList.stream().sorted(Comparator.reverseOrder());
        vo.setCateIds(cateList);

        return vo;
    }

    @Override
    public List<ProductVo> listProduct() {
        return baseMapper.listProduct(UserUtils.getStoreId());
    }

    @Override
    @Transactional
    public void saveProduct(ProductVo productVo) {
        //保存基本信息
        ProductInfoEntity baseProduct = new ProductInfoEntity();
        BeanUtils.copyProperties(productVo, baseProduct);
        this.save(baseProduct);

        //保存属性
        ProductAttrEntity attrEntity = new ProductAttrEntity();
        BeanUtils.copyProperties(productVo, attrEntity);
        attrEntity.setProductId(baseProduct.getProductId());
        productAttrService.save(attrEntity);

        //保存图片
        if(CollectionUtil.isNotEmpty(productVo.getPics())){
            List<ProductImageEntity> list = productVo.getPics().stream().map(image -> {
                image.setProductId(baseProduct.getProductId());
                return image;
            }).collect(Collectors.toList());
            productImageService.saveBatch(list);
        }
    }

    @Override
    @Transactional
    public void update(ProductVo productVo) {
        ProductInfoEntity baseProduct = new ProductInfoEntity();
        BeanUtils.copyProperties(productVo, baseProduct);
        this.updateById(baseProduct);

        ProductAttrEntity attrEntity = new ProductAttrEntity();
        BeanUtils.copyProperties(productVo, attrEntity);
        attrEntity.setProductId(baseProduct.getProductId());
        productAttrService.updateById(attrEntity);

        //删除原来图片
        LambdaQueryWrapper<ProductImageEntity> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(ProductImageEntity::getProductId, baseProduct.getProductId());
        productImageService.remove(imageWrapper);

        //添加新的图片
        if(CollectionUtil.isNotEmpty(productVo.getPics())){
            List<ProductImageEntity> list = productVo.getPics().stream().map(image -> {
                image.setImageId(null);
                image.setProductId(baseProduct.getProductId());
                return image;
            }).collect(Collectors.toList());
            productImageService.saveBatch(list);
        }
    }

    @Override
    public Integer getPriceCount(Integer priceType, Long storeId) {
        if (Objects.equals(priceType, 1)) {
            return baseMapper.getUpPriceCount(storeId);
        }
        return baseMapper.getDownPriceCount(storeId);
    }

    public void getAllCateIds(Set<Long> cateList, Long cateId){
        ProductCategoryEntity categoryEntity = productCategoryService.getById(cateId);
        cateList.add(cateId);
        if(categoryEntity != null && categoryEntity.getParentId() != null && categoryEntity.getParentId() != 0){
            getAllCateIds(cateList, categoryEntity.getParentId());
        }
    }

}